import {BaseUtil,Base64Util} from '@zkwq/business'
import {MOBILE_CLIENT_WIDTH,CACHE_KEY,STORE} from '@/constants'
import { mapState } from 'vuex'
import { toLogin,outLogin } from '../service/login'
export default{
  data(){
    return {
      isMobileClient:false,
      HKY_PREFIX_LOGO:"https://scholarin.cn/file/downloadbyfastdfspath?fastdfspath=",
      ignoreRoutes:['home',"NoPermission","Disabled","News","NewsDetail"],

      permissionPage:{
      },
      resourceTypeMap : {
        'journal': '期刊',
        'article': '论文',
        'video': '视频',
        'audio': '音频',
        'conference': '会议论文集',
        'text': '文字',
        'conferenceProceeding': '会议论文集',
        'conferenceArticle': '会议论文',
        'post': '文章',
        'patent': '专利',
        'standard': '标准',
        'report': '报告',
        'ebook': '电子书',
      },
      resourceActionMap : {
        'video': 3,
        'audio': 4,
        'text': 5,
        'post': 8,
        'patent': 9,
        'standard': 10,
        'report': 11,
        'ebook': 12,
      },
      VIDEO:"video",
      AUDIO:"audio",
      TEXT:"text",
      videoAudioTextActionMap:{
        'video': 3,
        'audio': 4,
        'text': 5,
      },
    }
  },
  created(){
    this.isMobileClient = document.body.clientWidth <= MOBILE_CLIENT_WIDTH
  },
  computed:{
    ...mapState(['user','roles','permissions','community','oauthUri','topic','topicId','appid','clientType','theme','magazine'])
  },
  methods:{
    toLogin,
    outLogin(){
      BaseUtil.removeStorage(CACHE_KEY.USER)
      BaseUtil.removeStorage(CACHE_KEY.ROLE)
      BaseUtil.removeStorage(CACHE_KEY.PERMISSION)
      BaseUtil.removeStorage(CACHE_KEY.TOKEN)
      outLogin()
    },
    APIParse(e,interceptCode = []){
      if(interceptCode.includes(e.code)){
          return e.data;
      }
      if(e.code == 0){
          return e?.data;
      }else if(e.code == -400){
          toLogin()
      }else if(e.code == -403){
          //跳转封禁页面
          // this.$router.push("/disabled")
          location.href = "/disabled"
          return;
      }else if(e.code == -404){
          //您不在当前群组内
          this.$router.push("/manager/group")
          return;
      }else if(e.code == -5){
          //您不在当前群组内
          
      }
      throw new Error(e.msg);
  },
    hasRole(roles,operator = 'OR'){
      let status = false;
      roles = roles || [];
      let sysRoles = (BaseUtil.getStorage(CACHE_KEY.ROLE) || []);
      if(operator == 'OR'){
          for(let i = 0; i < roles.length; i++){
              if((sysRoles.includes(roles[i]))){
                  status = true;
                  return status;
              }
          }
      }else{
          for(let i = 0; i < roles.length; i++){
              if((!sysRoles.includes(roles[i]))){
                  return status;
              }
          }
          status = true;
      }
      return status;
  },
  hasPermission(permissions,operator = 'OR'){
      let status = false;
      permissions = permissions || [];
      let sysPermissions = (BaseUtil.getStorage(CACHE_KEY.PERMISSION) || []);
      if(operator == 'OR'){
          for(let i = 0; i < permissions.length; i++){
              if((sysPermissions.includes(permissions[i]))){
                  status = true;
                  return status;
              }
          }
      }else{
          for(let i = 0; i < permissions.length; i++){
              if((!sysPermissions.includes(permissions[i]))){
                  return status;
              }
          }
          status = true;
      }
      return status;
  },
    gmv(expressionFun,trueVal,falseVal = false){
      try{
        if(typeof expressionFun === 'function'){
          let result = expressionFun();
          return result?(trueVal || result):falseVal
        }
        return expressionFun?(trueVal || expressionFun):falseVal
      }catch(ex){
        console.warn('$gmv',ex)
        return falseVal;
      }
    },
    isArrayEmpty:BaseUtil.isArrayEmpty,
    formatDisplayNumber:BaseUtil.formatNumber,
    arrayContains:BaseUtil.isArrayContains,
    openUrl(url){
      window.open(url)
    },
    clearHtml(str){
      str = str?.replace(/<[^>]+>/g, "");
      str = str?.replace(/&nbsp;/ig, "");
      return str;
    },
    checkLogin(){
      if(!this.user || this.user.anonymous){
        BaseUtil.setStorage('target_path', Base64Util.encode(location.href))
        location.href = this.oauthUri
        return false
      }
      return true
    },
    toNoPermission(){
      location.href = '/403'
    },
    setUser(user){
      this.$store.commit(STORE.SET_USER,user)
      BaseUtil.setStorage(CACHE_KEY.USER,user)
    }

  },
  beforeRouteEnter (to, from, next){
      next(vm => {
          if(vm.ignoreRoutes.includes(to.name) || vm.user){
              let needPermissions = vm.permissionPage[to.name] || {}
              if(!vm.hasPermission(needPermissions.permissions || [],needPermissions.operator || 'AND')){
                  //无权限访问当前页面
                  vm.toNoPermission();
              }

          }else{
              vm.toLogin();
          }
      });
  }
}